﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Web.Mvc;

namespace StarterKits.Mvc.Filters.FormsAuthentication
{
	/// <summary>
	/// Based on code originally published by Rob Conery:
	/// http://blog.wekeroad.com/blog/aspnet-mvc-securing-your-controller-actions/
	/// </summary>
	public class RequiresAnyRoleAttribute : BaseAuthenticationAttribute
	{

		public string Roles { get; set; }

		protected override bool IsValid( ActionExecutingContext filterContext )
		{
			string[] roles = Roles.Split(',');
			//redirect if the user is not authenticated
			if( roles != null && roles.Length > 0 )
			{

				if( !filterContext.HttpContext.User.Identity.IsAuthenticated )
					return false;
				else
				{
					foreach( string role in roles )
						if( filterContext.HttpContext.User.IsInRole( role ) )
							return true;
					return false;
				}

			}
			else
				throw new InvalidOperationException( "No Role Specified" );
		}

	}
}
